package com.menggudf.service.impl;

import com.menggudf.convert.EntityConvertUtil;
import com.menggudf.dao.BlackListDao;
import com.menggudf.dao.base.Page;
import com.menggudf.entity.BlackList;
import com.menggudf.model.BlackListModel;
import com.menggudf.model.ResultModel;
import com.menggudf.service.BlackListService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BlackListServiceImpl
  implements BlackListService
{
  private static final Logger LOGGER = LoggerFactory.getLogger(BlackListServiceImpl.class);
  @Autowired
  BlackListDao blackListDao;
  
  @Transactional(value="medicalTM", rollbackFor={Exception.class})
  public ResultModel add(String num, Integer type)
  {
    BlackList b = (BlackList)this.blackListDao.findBy(BlackList.class, "num", num);
    if (b != null) {
      return ResultModel.fail("已存在", b.getType());
    }
    BlackList nb = new BlackList();
    try
    {
      nb.setNum(num);
      nb.setType(type);
      this.blackListDao.persist(nb);
      return ResultModel.success("添加成功", null);
    }
    catch (Exception e)
    {
      LOGGER.error("add fail", e);
    }
    return ResultModel.fail("添加失败", null);
  }
  
  @Transactional(value="medicalTM", rollbackFor={Exception.class})
  public ResultModel del(int id)
  {
    try
    {
      BlackList b = this.blackListDao.findById(Integer.valueOf(id));
      if (b == null) {
        return ResultModel.fail("不存在", null);
      }
      this.blackListDao.remove(b);
      return ResultModel.success("删除成功", null);
    }
    catch (Exception e)
    {
      LOGGER.error("del fail", e);
    }
    return ResultModel.fail("删除失败", null);
  }
  
  @Transactional(value="medicalTM", readOnly=true)
  public Map<String, Object> list(String num, Integer type, int pageSize, int offset)
  {
    Page<BlackList> page = this.blackListDao.getBlackList(num, type, pageSize, offset);
    long total = page.getCount();
    List<BlackListModel> mlist = new ArrayList();
    if (total > 0L)
    {
      List<BlackList> list = page.getResultList();
      mlist = EntityConvertUtil.entity2Model(list, BlackListModel.class);
    }
    Map<String, Object> map = new HashMap();
    map.put("total", Long.valueOf(total));
    map.put("rows", mlist);
    return map;
  }
  
  @Transactional(value="medicalTM", readOnly=true)
  public List<BlackListModel> getListByType(int type)
  {
    List<BlackList> list = this.blackListDao.findListBy(BlackList.class, "type", Integer.valueOf(type));
    List<BlackListModel> mlist = EntityConvertUtil.entity2Model(list, BlackListModel.class);
    return mlist;
  }
}
